package com.ls.search;

import java.util.ArrayList;

/**
 * 二分查找
 * 必须是有序数组
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {3, 7, 9, 9, 9, 9, 10, 10, 11};
        BinarySearch binarySearch = new BinarySearch();
        System.out.println(binarySearch.search(arr, 0, arr.length - 1, 9));


        binarySearch.search2(arr, 0, arr.length - 1, 9).stream()
                .forEach(System.out::println);
    }

    /**
     * @param arr
     * @param left  始索引
     * @param right 终索引
     * @param value
     * @return
     */
    public int search(int[] arr, int left, int right, int value) {

        int mid = (left + right) / 2;
        int midval = arr[mid];
        if (left > right) {
            return -1;
        }
        if (value < midval) {
            return search(arr, left, mid - 1, value);
        } else if (value > midval) {
            return search(arr, mid + 1, right, value);
        } else {
            return mid;
        }
    }

    /**
     * @param arr
     * @param left  始索引
     * @param right 终索引
     * @param value
     * @return
     */
    public ArrayList search2(int[] arr, int left, int right, int value) {

        int mid = (left + right) / 2;
        int midval = arr[mid];
        if (left > right) {
            return null;
        }
        if (value < midval) {
            return search2(arr, left, mid - 1, value);
        } else if (value > midval) {
            return search2(arr, mid + 1, right, value);
        } else {
            ArrayList<Integer> arrayList = new ArrayList<>();

            //向mid索引值的左侧扫描将所有满足的元素加入到ArrayList
            int temp = mid - 1;
            while (true) {
                if (temp < 0 || arr[temp] != value) {
                    break;
                }
                arrayList.add(temp);
                temp--;
            }
            arrayList.add(mid);

            temp = mid + 1;
            while (true) {
                if (temp > arr.length - 1 || arr[temp] != value) {
                    break;
                }
                arrayList.add(temp);
                temp++;
            }
            return arrayList;
        }
    }
}
